package com.edais.mina;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class ClientMinaServerHandler extends IoHandlerAdapter {
	private static final Logger logger = Logger.getLogger(ClientMinaServerHandler.class);
	
	private final AtomicInteger count = new AtomicInteger(0);
	
	@Override
	public void sessionCreated(IoSession session) {
	}
	
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.debug("Mina session opened-sessionid:" + session.getId() + "-count:" + count.incrementAndGet());
	}
	
	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		logger.debug("Mina session messageReceived-sessionid:" + session.getId());
	}
	
	@Override
	public void messageSent(IoSession session, Object message) {
		logger.debug("Mina session sent-sessionid:" + session.getId());
	}
	
	@Override
	public void sessionClosed(IoSession session) {   
		logger.info("Mina session closed-sessionid:" + session.getId() + "-count:" + count.decrementAndGet());
	}   
	
	@Override    
	public void sessionIdle(IoSession session, IdleStatus status) {        
		logger.error("Mina session idle-sessionid:" + session.getId() + "-count:" + count);
		session.close(true);
	}
	
	@Override    
	public void exceptionCaught(IoSession session, Throwable cause) {
		logger.error("Mina session 异常-sessionid:" + session.getId() + "-count:" + count, cause);
		session.close(true);
	}
}